package com.company.myapplication;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.company.myapplication.bean.UpLoadHeadModel;
import com.company.myapplication.utils.StringUtils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import net.callback.SimpleObserver;
import net.http.HttpManager;
import net.http.MineServiceApi;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getName();
    private TextView tvDeviceId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initPermission();
    }

    private void initView() {
        tvDeviceId = findViewById(R.id.device_id_tv);
        tvDeviceId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upLoadAvatar();
            }
        });
    }

    private void upLoadAvatar() {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(MediaType.parse("files/*"), "/pvl01/firmware/test/20210907/1630995653869.jpg");
        builder.setType(MultipartBody.FORM)
                .addFormDataPart("userId", "3ecdc3fc-4e9b-4c60-820f-fb486480396f")
                .addFormDataPart("file", "1631029799585.jpg", requestBody);
        List<MultipartBody.Part> parts = builder.build().parts();
        Observable<UpLoadHeadModel> call = HttpManager.get()
                .localBaseUrl(HttpManager.getInstance().baseUrl)
                .getApiService(MineServiceApi.class)
                .postFile(parts);
        HttpManager.get().subscriber(call, new SimpleObserver<UpLoadHeadModel>() {
            @Override
            public void onSuccess(UpLoadHeadModel upLoadHeadModel) {
                Log.d(TAG, "--code--" + upLoadHeadModel.getCode() + "data" + upLoadHeadModel.getData());
                if (upLoadHeadModel.getCode() == 0) {
                    Toast.makeText(MainActivity.this, "上传图片成功", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Log.d(TAG, msg);
            }
        });
    }

    private void initPermission() {
        final RxPermissions rxPermissions = new RxPermissions(this);
        final StringBuilder rationaleSb = new StringBuilder();
        final StringBuilder deniedSb = new StringBuilder();
        String[] permissionStrArray = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE};
        rxPermissions.requestEach(permissionStrArray).subscribe(new Observer<Permission>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Permission permission) {
                if (permission.granted) {
                    // 用户已经同意该权限
                    Log.d(TAG, "权限：" + permission.name + " 已开启");
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时。还会提示请求权限的对话框
                    Log.d(TAG, "权限：" + permission.name + " 权限拒绝，但没有选中 不再询问");
                    if (rationaleSb.toString().contains(StringUtils.getPermissionName(permission.name))) {
                        return;
                    }
                    rationaleSb.append(StringUtils.getPermissionName(permission.name));
                    rationaleSb.append("、");
                } else {
                    // 用户拒绝了该权限，而且选中『不再询问』
                    Log.d(TAG, "权限：" + permission.name + " 权限拒绝，并且选中 不再询问");
                    if (deniedSb.toString().contains(StringUtils.getPermissionName(permission.name))) {
                        return;
                    }
                    deniedSb.append(StringUtils.getPermissionName(permission.name));
                    deniedSb.append("、");
                }
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "permission  onError");
            }

            @Override
            public void onComplete() {
                if (TextUtils.isEmpty(rationaleSb) && TextUtils.isEmpty(deniedSb)) {
                    Log.d(TAG, "permission.name ,权限已经允许");
                    upLoadAvatar();
                } else {
                    if (!TextUtils.isEmpty(deniedSb)) {
                        showTipDialog(deniedSb, 0);
                    } else if (!TextUtils.isEmpty(rationaleSb)) {
                        showTipDialog(rationaleSb, 1);
                    }
                }
            }
        });
    }

    /**
     * 权限请求拒绝逻辑
     *
     * @param permissionName
     * @param permissionType
     */
    private void showTipDialog(StringBuilder permissionName, int permissionType) {

    }
}